package org.gruposp2p.dnie.server.extras;

import org.springframework.dao.DataAccessException;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.gruposp2p.dnie.model.DNIeUser;
import org.gruposp2p.dnie.service.DNIeUserDAO;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;
import javax.servlet.http.HttpServletRequest;
import org.gruposp2p.dnie.model.DNIeAuthority;
import org.gruposp2p.dnie.model.DNIePrincipal;
import org.gruposp2p.dnie.utils.DateUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 *
 * @author jj
 */
@Service("dnieUserDetailsService")
public class DNIeUserDetailsService implements UserDetailsService {

    private static Logger logger =
            LoggerFactory.getLogger(DNIeUserDetailsService.class);

    @Autowired
    private DNIeUserDAO userDao;

    public UserDetails loadUserByUsername(String login)
            throws UsernameNotFoundException, DataAccessException {
        logger.debug("loadUserByUsername - login: " + login);
        DNIeUser user = userDao.findByNif(login);
        if (user == null) {
            //throw new UsernameNotFoundException("user not found in database");
            HttpServletRequest request = ((ServletRequestAttributes)
                    RequestContextHolder.getRequestAttributes()).getRequest();
            X509Certificate[] certs = (X509Certificate[])request.getAttribute(
                    "javax.servlet.request.X509Certificate");
            if (certs != null) {
                X509Certificate cert = certs[0];
                DNIePrincipal dniePrincipal = new DNIePrincipal (
                        cert.getSubjectX500Principal().getName(X500Principal.RFC1779));
                DNIeUser newUser = new DNIeUser();
                newUser.setName(dniePrincipal.CN);
                newUser.setNif(dniePrincipal.SERIALNUMBER);
                newUser.setDateAdded(DateUtils.getTodayDate());
                newUser.setEnabled(Boolean.TRUE);
                newUser.setAuthority(DNIeAuthority.ROLE_USER);
                user = userDao.save(newUser);
            }     
        }
        return user;
    }

}